package com.rahms.server.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.rahms.common.constant.AutoFillConstant;
import com.rahms.common.context.UserContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 配置类
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 自动填充处理器
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                // 自动填充创建时间
                this.strictInsertFill(metaObject, AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
                // 自动填充创建用户
                Long currentUserId = UserContext.getCurrentUserId();
                if (currentUserId != null) {
                    this.strictInsertFill(metaObject, AutoFillConstant.SET_CREATE_USER, Long.class, currentUserId);
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                // 自动填充更新时间
                this.strictUpdateFill(metaObject, AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
                // 自动填充更新用户
                Long currentUserId = UserContext.getCurrentUserId();
                if (currentUserId != null) {
                    this.strictUpdateFill(metaObject, AutoFillConstant.SET_UPDATE_USER, Long.class, currentUserId);
                }
            }
        };
    }
}
